package com.jn.news.net;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {
    // 默认 baseUrl（可选）
    private static final String DEFAULT_BASE_URL = "https://apis.tianapi.com/";

    // ✅ 使用 Map 缓存多个 baseUrl 对应的实例
    private static final ConcurrentHashMap<String, RetrofitClient> instances = new ConcurrentHashMap<>();

    private ApiService apiService;

    private RetrofitClient(String baseUrl) {
        // 创建日志拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .build();

        apiService = retrofit.create(ApiService.class);
    }

    /**
     * 获取指定 baseUrl 的 RetrofitClient 实例（线程安全，懒加载）
     */
    public static RetrofitClient getInstance(String baseUrl) {
        // ✅ 如果 baseUrl 为空，使用默认值
        if (baseUrl == null || baseUrl.trim().isEmpty()) {
            baseUrl = DEFAULT_BASE_URL;
        }

        // ✅ 如果该 baseUrl 的实例不存在，则创建
        return instances.computeIfAbsent(baseUrl, k -> new RetrofitClient(k));
    }

    /**
     * 清除某个 baseUrl 的实例（可选：用于动态更新配置）
     */
    public static void clearInstance(String baseUrl) {
        instances.remove(baseUrl);
    }

    /**
     * 清除所有实例（测试或重启时使用）
     */
    public static void clearAll() {
        instances.clear();
    }

    public ApiService getApiService() {
        return apiService;
    }
}